package com.sky.controller.admin;


import com.sky.result.Result;
import com.sky.utils.BitifulS3Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author majun
 * @package com.sky.controller.admin
 * @date 2025/6/21 10:47
 */
@Slf4j
@RestController
@RequestMapping("/admin/upload")
public class UpataFileController {

    @Autowired
    private BitifulS3Util bitifulS3Util;

    @PostMapping("/file")
    private Result upload(MultipartFile file) {
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            log.warn("上传文件为空");
            return Result.error("请选择要上传的文件");
        }

        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.trim().isEmpty()) {
            log.warn("文件名为空");
            return Result.error("文件名不能为空");
        }

        // 检查文件类型是否为图片
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            log.warn("文件类型不是图片，contentType={}", contentType);
            return Result.error("只能上传图片文件");
        }

        // 获取文件扩展名
        String extension = "";
        int lastDotIndex = originalFilename.lastIndexOf(".");
        if (lastDotIndex > 0) {
            extension = originalFilename.substring(lastDotIndex);
        }

        // 生成唯一文件名，防止重复
        String uniqueFilename = UUID.randomUUID().toString() + extension;
        
        log.info("准备上传文件，原始文件名={}, 生成文件名={}, 文件大小={} bytes", 
                originalFilename, uniqueFilename, file.getSize());

        try {
            bitifulS3Util.uploadFile(uniqueFilename, file);
            log.info("文件上传成功，文件名={}", uniqueFilename);
            
            // 生成自定义域名访问URL
            String fileUrl = bitifulS3Util.generateCustomDomainUrl(uniqueFilename);
            
            // 返回文件信息
            Map<String, String> fileInfo = new HashMap<>();
            fileInfo.put("filename", uniqueFilename);
            fileInfo.put("originalName", originalFilename);
            fileInfo.put("url", fileUrl);
            fileInfo.put("size", String.valueOf(file.getSize()));
            fileInfo.put("contentType", contentType);
            
            return Result.success(fileInfo);
        } catch (IOException e) {
            log.error("文件上传失败，文件名={}", uniqueFilename, e);
            return Result.error("上传失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("文件上传异常，文件名={}", uniqueFilename, e);
            return Result.error("上传异常: " + e.getMessage());
        }
    }

}
